<template> 
  <div>
    <div id="machine"
         v-loading="loading"
         element-loading-text="数据获取中..."
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)"
        >
        <el-image-viewer 
          v-if="screenimgshow"
          :on-close="closeViewer"
          v-bind:url-list="[screenimg]">
        </el-image-viewer>   
        <div class="comspreadstat clearfix" v-if="goodsordertotal.length">
            <span class="spread-item1"> <router-link :to="''" @click.native="getgoodsorderlist(0,0,1,'今日订单')">今日<b>&yen;{{ goodsordertotal[0].goodsmoney }} / {{ goodsordertotal[0].goodsamount }}单 </b></router-link></span>
            <span class="spread-item1"> <router-link :to="''" @click.native="getgoodsorderlist(1,0,1,'昨日订单')">昨日<b>&yen;{{ goodsordertotal[1].goodsmoney }} / {{ goodsordertotal[1].goodsamount }}单</b> </router-link></span>
            <span class="spread-item1"> <router-link :to="''" @click.native="getgoodsorderlist(2,0,1,'本月订单')">月总计<b>&yen;{{ goodsordertotal[2].goodsmoney }} / {{ goodsordertotal[2].goodsamount }}单</b> </router-link></span>
            <span class="spread-item1"> <router-link :to="''" @click.native="getgoodsorderlist(3,0,1,'上月订单')">上月总计<b>&yen;{{ goodsordertotal[3].goodsmoney }} / {{ goodsordertotal[3].goodsamount }}单</b> </router-link></span>
            <span class="spread-item1"> <router-link :to="''" @click.native="">月退款<b>&yen;  0</b> </router-link></span>
        </div>
        <header class="Thead2" style="text-align: left;"> {{ pagetitle }}</header>

        <div id="ulist">
            <section class="ulist clearfix" v-for="(item, index) in goodsorderList" :key="index">
                <div class="info" style="text-align: left;">
                  <p>出货机：<b>{{ item.machinename }}</b> 订单号：<b> {{ item.trade_sn }}</b></p>
                  <p>售卖商品: <b>{{ item.goodsname }}</b> 支付状态:<b v-show="item.status=='unpay'">未付款</b><b v-show="item.status=='succ'">已付款</b></p>
                  <p>付款方式：<b>{{ item.payment }}</b> 支付金额：<b>&yen; {{ item.money }}</b> 出货状态:<b v-show="item.shipment==0">未出货</b><b v-show="item.shipment==1">已出货</b></p>
                  <p>出货量：<b>{{ item.amount }}</b> 剩余数量：<b>{{ item.curamount }}</b> 货道：<b>{{ item.cargoway }}</b> 出售日期：<b>{{ item.addtime*1000 | formatDate }}</b></p>
                </div>
            </section>
        </div>
    </div>
    <Topnav></Topnav>
    <div class="bottom_nav">
      <router-link class="nav_index" :to="'/'"><i></i>上货</router-link>
      <router-link class="nav_search" :to="{ path: '/Chart/' + machineid }"><i></i>销售统计</router-link>  
      <router-link class="nav_shopcart" :to="''" @click.native="screenshot()"><i></i>机器桌面</router-link>
      <router-link class="nav_me" :to="''" @click.native="camerashot()"><i></i>机器摄像头</router-link>
    </div>
  </div>
</template>

<script>
import mqtt from 'mqtt';
import axios from 'axios';  
import Topnav from "./topnav.vue";
import {formatDate} from './date.js';

// 导入组件
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

export default {
  name: 'machine',
  props: {

  },  
  data () {
    return {
       machineid : 0,
       screenimg : '',
       loading : false,
       screenimgshow : false, 
       esp32camstring : '',
       pagetitle : '今日订单',
       goodsorderList: {
          type: Array,
          default: () => []
       },
       goodsordertotal: {
          type: Array,
          default: () => []
       },  
    }
  },  
  components: {
    Topnav,
    ElImageViewer
  },    
  mounted: function() { 
    this.machineid = this.$route.params.machineid;
    this.loading=true;
    this.InitMqtt(); 
    this.getgoodsorderlist(0,0,1,'今日订单');   
    this.loading=false;
  }, 
  destroyed: function () {
    console.log("Machine leave.");
    this.$GLOBAL.mqttclient.end();
  },
  filters: {
      formatDate(time) {
          var date = new Date(time);
          return formatDate(date, 'yyyy-MM-dd hh:mm');
      }
  },
  methods: {
    // 关闭查看器
    closeViewer() {
     this.screenimgshow = false
    },
    getgoodsorderlist(ptype,pnum,isupdate,title) {
      var self = this;

      this.pagetitle = title;

      var location = 'http://cms.o4.com/mobilegetgoodsorders';

      var userinfo = this.$cookies.get('userinfo');
      axios.get(location, {
          params: {
            userid: userinfo.id,
            machineid:self.machineid,
            type:ptype,
            num:pnum
          }
        })
        .then(function (response) {
          //console.log(response.data);

          if(isupdate) {
            self.goodsorderList = response.data;      
          }
          else {
            self.goodsorderList.unshift(response.data[0]);
          }  
        })
        .catch(function (error) {
          console.log(error);
        });

      var location2 = 'http://cms.o4.com/mobilegetgoodsordertotal';

      axios.get(location2, {
          params: {
            userid: userinfo.id,
            machineid:self.machineid,
          }
        })
        .then(function (response) {
           //console.log(response.data);
           self.goodsordertotal = response.data;      
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    camerashot: function() {
        var self = this;

        /*var userinfo = self.$cookies.get('userinfo');
        var str = 'super/machine/camera/' + userinfo.id;

        //订阅主题 presence
        this.mqttclient.subscribe(str, function (err) {
          if (!err) {
             console.log(str+" 订阅成功.")

             var qtt = {}; //定义消息（可以为字符串，对象等）
             qtt.machineid = self.machineid;
             qtt.playerid = userinfo.id;

             self.mqttclient.publish('super/machine/camera',JSON.stringify(qtt),{ qos: 0, retain: false })
          }else{
          //打印错误
            console.log(err)
          }
        })*/

       var qtt = {}; //定义消息（可以为字符串，对象等）
       qtt.action = "on";

       this.mqttclient.publish('takepicture',JSON.stringify(qtt),{ qos: 0, retain: false }) 
    },    
    screenshot: function() {
        var self = this;

        this.$GLOBAL.mqttloading = this.$loading({
          lock: true,
          text: '请稍后...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        var userinfo = self.$cookies.get('userinfo');
        var str = 'super/machine/screenshot/' + userinfo.id;

        //订阅主题 presence
        this.$GLOBAL.mqttclient.subscribe(str, function (err) {
          if (!err) {
             console.log(str+" 订阅成功.")

             var qtt = {}; //定义消息（可以为字符串，对象等）
             qtt.machineid = self.machineid;
             qtt.playerid = userinfo.id;

             self.$GLOBAL.mqttclient.publish('super/machine/screenshot',JSON.stringify(qtt),{ qos: 0, retain: false })
          }else{
          //打印错误
            console.log(err)
          }
        })     
    },
    InitMqtt: function () {
      var self = this;

     var options = {
    //mqtt客户端的id，这里面应该还可以加上其他参数，具体看官方文档
      clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
      //username:'admin',
      //password:'112233',   
    }    

      this.mqttclient = mqtt.connect("ws://mq.tongxinmao.com:18832/mqtt",options) // you add a ws:// url here
      this.$GLOBAL.mqttclient = this.mqttclient;

      //建立连接
      this.mqttclient.on('connect', function () {
        console.log("中心服务器连接成功!")

        var subscribes = ['super/machine/goline',
                          'super/machine/offline',
                          'home/photo/start',
                          'home/photo/data',
                          'home/photo/end'];
        //订阅主题 presence
        self.mqttclient.subscribe(subscribes, function (err) {
          if (!err) {
            console.log("中心服务器消息订阅成功!")
          }else{
          //打印错误
            console.log(err)
          }
        })    

        subscribes = ['super/machine/shipment/return/'+this.machineid];   
           
        self.mqttclient.subscribe(subscribes, {qos:0},function (err) {
          if (!err) {
            console.log("中心服务器qos2消息订阅成功!")
          }else{
          //打印错误
            console.log(err)
          }
        })            
      })
      
      //如果连接错误，打印错误
      this.mqttclient.on('error', function (err) {
        console.log(err)
        self.mqttclient.end()
      })

      //如果client订阅主题成功，那么这里就是当接收到自己订阅主题的处理逻辑
      this.mqttclient.on('message', function (topic, message) {
        // message is Buffer,此处就是打印消息的具体内容
        var msg = message.toString();
        var topicstr = topic.toString();

        if(topicstr == 'home/photo/data') {
           self.esp32camstring += msg;
           return; 
        }

        console.log(topicstr + ":" + msg);

        var userinfo = self.$cookies.get('userinfo');
        var str = 'super/machine/screenshot/' + userinfo.id;
        var str2 = 'super/machine/camera/' + userinfo.id;

         try{ 
          var params = JSON.parse( message.toString() );

          if(topicstr == str) {
            if(params.screenshot_img) {
              self.screenimg = params.screenshot_img;            
            }

            //self.screenimgList.push(self.screenimg);
            self.screenimgshow = true;
            self.$GLOBAL.mqttloading.close();
            self.$GLOBAL.mqttclient.unsubscribe(str, function (err) {
              if (!err) {
                console.log(str+" 退订成功!")
              }else{
              //打印错误
                console.log(err)
              }
            })
          }
          else if(topicstr == str2) {
            if(params.camera_img) {
              self.screenimg = params.camera_img;            
            }

            //self.screenimgList.push(self.screenimg);
            self.screenimgshow = true;
            self.$GLOBAL.mqttloading.close();
            self.$GLOBAL.mqttclient.unsubscribe(str2, function (err) {
              if (!err) {
                console.log(str2+" 退订成功!")
              }else{
              //打印错误
                console.log(err)
              }
            })
          }
          else if(topicstr == 'super/machine/shipment/return/'+this.machineid) {
            if(params.state == 1) {
              console.log(msg); 
              self.$message('你有一个新的订单，请查收！'); 
              new Audio(
                'http://tts.baidu.com/text2audio?cuid=baiduid&lan=zh&ctp=1&pdt=311&tex=你有一个新的订单请查收'
              ).play();

              //获取新的订单
              self.getgoodsorderlist(0,1,0,'今日订单');  
            }
          }
          else if(topicstr == 'home/photo/start') {
            //self.esp32camstring='data:image/jpeg;base64,'; 
            self.esp32camstring='';

            self.$GLOBAL.mqttloading = self.$loading({
              lock: true,
              text: '请稍后...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
          }
          else if(topicstr == 'home/photo/end') {
            //console.log(self.esp32camstring);
            self.screenimg = 'data:image/jpeg;base64,' + self.esp32camstring;            

            //self.screenimgList.push(self.screenimg);
            self.screenimgshow = true;
            self.$GLOBAL.mqttloading.close();

            var location = 'http://cms.o4.com/baiduFacerecognition';
              
            var bodys = "[{\"image\": \""+self.esp32camstring+"\", \"image_type\": \"BASE64\", \"face_type\": \"LIVE\", \"quality_control\": \"LOW\"},{\"image\": \""+self.esp32camstring+"\", \"image_type\": \"BASE64\", \"face_type\": \"IDCARD\", \"quality_control\": \"LOW\"}]";      

            axios.post(location,{      
                params:bodys,
                }).then(function(res){
                    if(res.data.error_code != 0) {
                      console.log(res.data.error_msg);
                    }
                    else {
                      console.log(res.data.result.score);

                      new Audio(
                        'http://tts.baidu.com/text2audio?cuid=baiduid&lan=zh&ctp=1&pdt=311&tex=主人您好 您辛苦了 欢迎回家'
                      ).play();
                    }
                }).catch(function (error) {
                    console.log(error);
                });  
          }  

         }catch(exception){
          console.info(exception.message);
         } 
      })
    }
  }  
}
</script>

<style>
.home-recom {
  width: 100%;  
  text-align: center;
}
.hplist {
  width: 48%;
  margin-right: 2%;
  margin-top: 10px;
  float: left;
  background: #f7f7f7;
  display: inline;
  position: relative;
  z-index: 1;
}
.img1 {
  display: block;
  width: 100%;
  z-index: 1
}
.spread-item1 {
   width: 20%;
   display: inline-block;
   float: left;
   margin: 10px 0;
   font-size: 10pt;
   text-align: center;
   border-right: 1px solid #dedede;
   margin-left: -1px;
}
.spread-item1:last-child {
   border: none;
   margin-left: 0;
}
.spread-item1 i {
   display: block;
   width: 50px;
   height: 0;
   border-bottom: 1px dashed #dedede;
   margin: 3px auto;
   margin-top: 5px;
}
.spread-item1 b {
   display: block;
   font-size: 12px;
   font-weight: normal;
   margin-top: 4px;
   font-family: Verdana;
   color: #ff5500;
}
.Thead2 {
  position: relative;
  font-size: 15px;
  color: #888;
  border-left: 5px solid #44b549;
  padding-left: 10px;
  margin: 12px 10px;
}
</style>
